Skip to content

fix(sw): prevent media 401s by caching session tokens and retrying on auth failure#613

Draft
Just-Insane wants to merge 3 commits intoSableClient:devfrom
Just-Insane:fix/media-401-sw-retry
Draft

fix(sw): prevent media 401s by caching session tokens and retrying on auth failure#613
Just-Insane wants to merge 3 commits intoSableClient:devfrom
Just-Insane:fix/media-401-sw-retry

Conversation

@Just-Insane
Copy link
Copy Markdown
Contributor

Related to closed PR #548 (fix/media-error-handling), which was split into smaller focused PRs.

Description

Media fetches (thumbnails, file attachments, URL preview images) were failing with 401 after a token refresh or SW restart because the service worker had no mechanism to receive updated credentials. This fix:

  1. Calls sendSessionToSW() synchronously before React renders so the SW has a fresh token before any <img> fetch events arrive.
  2. Wires an onTokenRefresh callback into buildClient/initMatrix so new tokens are pushed to the SW immediately after a silent token refresh.
  3. Adds 401 detection in image and URL preview components — on auth failure the component clears the cached URL and retries with a cache-busting request.
  4. Caches successful sliding sync probe results for 10 minutes in localStorage to avoid an unnecessary 300–5000 ms network round-trip on every cold start.

Fixes #

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • My changes generate no new warnings

AI disclosure:

  • Partially AI assisted (clarify which code was AI assisted and briefly explain what it does).
  • Fully AI generated (explain what all the generated code does in moderate detail).

The session token caching and push logic in sw.ts, the onTokenRefresh callback threading through buildClient/initMatrix, and the 401 retry in ImageContent/UrlPreview were partially AI assisted. I reviewed the race condition window, token lifecycle, and cache-bust correctness.

@Just-Insane Just-Insane requested review from 7w1 and hazre as code owners March 31, 2026 18:43
@Just-Insane Just-Insane marked this pull request as draft March 31, 2026 20:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant